import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Button, message, DatePicker } from 'antd';
import { useNavigate } from 'react-router-dom';
import { getAssetList, createBorrow, permitUpdate } from '../../services/api';
import moment from 'moment';

const BorrowForm = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [assetList, setAssetList] = useState([]);

  // 从sessionStorage获取用户信息
  const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}');
  const isAdmin = userInfo.admin === 'yes';

  useEffect(() => {
    fetchAssetList();
  }, []);

  const fetchAssetList = async () => {
    try {
      const response = await getAssetList();
      if (response.code === 200) {
        setAssetList(response.data);
      } else {
        message.error('获取资产列表失败');
      }
    } catch (error) {
      console.error('获取资产列表失败:', error);
      message.error('获取资产列表失败');
    }
  };

  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      
      // 创建借用记录
      const createResponse = await createBorrow({
        uId: userInfo.uId,
        assetId: values.assetId,
        borrowNum: values.borrowNum,
        borrowStatus: isAdmin ? '已借出' : '待审批',
        borrowTime: moment().format('YYYY-MM-DD'),
        expectedReturnTime: values.expectedReturnTime.format('YYYY-MM-DD'),
        borrowReason: values.borrowReason
      });

      if (createResponse.code === 200) {
        // 如果是管理员直接借出，需要更新资产数量
        if (isAdmin) {
          const updateAssetResponse = await permitUpdate(values.assetId, {
            assetNum: values.borrowNum,
            assetStatus: 'lendout' // 操作类型：借出
          });

          if (updateAssetResponse.code !== 200) {
            message.error('更新资产数量失败');
            return;
          }
        }

        message.success(isAdmin ? '借用成功' : '借用申请已提交，请等待审批');
        navigate('/borrows');
      } else {
        message.error(createResponse.message || '提交失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <h2>借用申请</h2>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          name="assetId"
          label="资产"
          rules={[{ required: true, message: '请选择资产' }]}
        >
          <Select placeholder="请选择资产">
            {assetList.map(asset => (
              <Select.Option key={asset.assetId} value={asset.assetId}>
                {asset.assetName} (可用数量: {asset.assetNum})
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="borrowNum"
          label="借用数量"
          rules={[
            { required: true, message: '请输入借用数量' },
            {
              validator: async (_, value) => {
                if (value <= 0) {
                  throw new Error('借用数量必须大于0');
                }
                const selectedAsset = assetList.find(
                  asset => asset.assetId === form.getFieldValue('assetId')
                );
                if (selectedAsset && value > selectedAsset.assetNum) {
                  throw new Error('借用数量不能超过可用数量');
                }
              },
            },
          ]}
        >
          <Input type="number" placeholder="请输入借用数量" />
        </Form.Item>

        <Form.Item
          name="expectedReturnTime"
          label="预计归还时间"
          rules={[{ required: true, message: '请选择预计归还时间' }]}
        >
          <DatePicker
            format="YYYY-MM-DD"
            placeholder="请选择预计归还时间"
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item
          name="borrowReason"
          label="借用原因"
          rules={[{ required: true, message: '请输入借用原因' }]}
        >
          <Input.TextArea
            placeholder="请输入借用原因"
            rows={4}
          />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            {isAdmin ? '直接借出' : '提交申请'}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default BorrowForm; 